<script setup>
 import { nextTick, ref } from 'vue'
 import ChannelSelect from './ChannelSelect.vue'
 import { Plus } from '@element-plus/icons-vue';
 import { QuillEditor } from '@vueup/vue-quill'
 import '@vueup/vue-quill/dist/vue-quill.snow.css';
 import {artPublishService,artGetDetailService,artEditService} from '@/api/article.js'
 import { ElMessage } from 'element-plus';
 import {baseURL} from '@/utils/request.js'
 import axios from 'axios';

 const visibleDrawer= ref(false) //控制抽屉的显示和隐藏
 
 const defaultForm={
     title:'', //标题
     cate_id:'', //分类Id
     content:'', //富文本编辑器
     cover_img:'', //文章图片 file对象
     state:'' //文章状态
 }

 const imgUrl=ref('') // 默认图片地址
 
 //  准备数据
 const formModel = ref({
    ...defaultForm
 })
 const editorRef=ref()

 const open=async (row)=>{
    visibleDrawer.value=true
    console.log(row);
    if(row.id){
        // 编辑文章
        const res = await artGetDetailService(row.id)
        console.log(res);
        formModel.value=res.data.data
        imgUrl.value=baseURL+res.data.data.cover_img
        //这里后台提供给的图片地址是字符串 以后的提交修改是要提交file格式的图片 
        const file= await imageUrlToFile(imgUrl.value,formModel.value.cover_img)
        formModel.value.cover_img=file
    }else{
        // 每一次添加文章的时候都得清空表单 基于默认的数据，重置form数据
        formModel.value={...defaultForm}
        imgUrl.value=''
        await nextTick(()=>{
            editorRef.value.setHTML('')
        })
        // 添加文章
    }
 }
 const onSelectFile=(File)=>{
    console.log(File);
    imgUrl.value=URL.createObjectURL(File.raw)
    // 立刻将数据存入cover_img 将来用于提交
    formModel.value.cover_img=File.raw
 }
 const emit=defineEmits(['success'])
//  发布或编辑
 const onPublish=async (state)=>{
    formModel.value.state=state
    // 因为当前接口需要的是fromData对象 要转换一下
    const fd=new FormData()
    for(let key in formModel.value){
        fd.append(key,formModel.value[key])
    }

    if(formModel.value.id){
        console.log('编辑操作');
        await artEditService(fd)
        ElMessage.success('修改成功！')
        visibleDrawer.value=false
        // 通知父组件添加成功了
        emit('success','edit')
    }else{
        // 添加操作
        await artPublishService(fd)
        ElMessage.success('添加成功')
        visibleDrawer.value=false
        // 通知父组件添加成功了
        emit('success','add')
    }
 }
 // 将网络图片地址转换为File对象
async function imageUrlToFile(url, fileName) {
  try {
    // 第一步：使用axios获取网络图片数据
    const response = await axios.get(url, { responseType: 'arraybuffer' });
    const imageData = response.data;

    // 第二步：将图片数据转换为Blob对象
    const blob = new Blob([imageData], { type: response.headers['content-type'] });

    // 第三步：创建一个新的File对象
    const file = new File([blob], fileName, { type: blob.type });

    return file;
  } catch (error) {
    console.error('将图片转换为File对象时发生错误:', error);
    throw error;
  }
}

 defineExpose({
    open
 })
</script>

<template>
    <el-drawer
      v-model="visibleDrawer"
      :title="formModel.id ? '编辑文章' : '添加文章'"
      direction="rtl"
      size="50%"
    >
      <!-- 发表文章表单 -->
      <el-form :model="formModel" ref="formRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formModel.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <channel-select
            v-model="formModel.cate_id"
            width="100%"
            style="width:100%"
          ></channel-select>
        </el-form-item>
        <el-form-item label="文章封面" prop="cover_img"> 
            <el-upload  class="avatar-uploader" :show-file-list="false" :auto-upload="false" :on-change="onSelectFile">
                <img v-if="imgUrl" :src="imgUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>  
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <div class="editor">
            <!-- 富文本编辑器 -->
            <quill-editor v-model:content="formModel.content" theme="snow" content-type="html" ref="editorRef"></quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="onPublish('已发布')" type="primary">发布</el-button>
          <el-button @click="onPublish('草稿')" type="info">草稿</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </template>
  
  <style scoped lang="scss">
    .avatar-uploader {
        :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }
        .el-upload:hover {
            border-color: var(--el-color-primary);
        }
        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
        }
    }
   </style>